/* Copyright(c) 2017-2019 Alejandro Sirgo Rica & Contributors
*               2020 KylinSoft Co., Ltd.
* This file is part of Kylin-Screenshot.
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "textwidget.h"

TextWidget::TextWidget(QWidget *parent) : QTextEdit(parent)
{
    setStyleSheet(QStringLiteral("TextWidget { background: transparent; }"));
    connect(this, &TextWidget::textChanged,
            this, &TextWidget::emitTextUpdated);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setContextMenuPolicy(Qt::NoContextMenu);
    document()->setDocumentMargin(0);
    setWordWrapMode(QTextOption::WrapAnywhere);
}

void TextWidget::setMaxSize(int max_Width, int max_Height)
{
    max_width = max_Width;
    max_height = max_Height;
}

void TextWidget::showEvent(QShowEvent *e)
{
    QTextEdit::showEvent(e);
    adjustSize();
}

void TextWidget::resizeEvent(QResizeEvent *e)
{
    QTextEdit::resizeEvent(e);
}

void TextWidget::setFont(const QFont &f)
{
    QTextEdit::setFont(f);
    adjustSize();
}

void TextWidget::updateFont(const QFont &f)
{
    setFont(f);
}

void TextWidget::setFontPointSize(qreal s)
{ 
    QFont f = font();
    f.setPointSize(s);
    setFont(f);
}

void TextWidget::setTextColor(const QColor &c)
{
    QString s(QStringLiteral("TextWidget { background: transparent; color: %1; }"));
    setStyleSheet(s.arg(c.name()));
}

void TextWidget::adjustSize()
{
    QString &&text = this->toPlainText();

    QFontMetrics fm(font());

    document()->adjustSize();
    int pixelsWide = document()->size().width() + fm.lineSpacing();
    document()->setTextWidth(max_width-5); // 预留5px，避免输入单行最后一个字符被挤，导致文字总体左移
    int pixelsHigh = document()->size().height(); // setTextWidth限制宽度触发自动换行后，再获取高度
    pixelsWide = qBound(5, pixelsWide, max_width);
    pixelsHigh = qBound(fm.lineSpacing()+5, pixelsHigh+5, max_height);// 预留5px，避免换行文字总体上移
    this->setFixedSize(pixelsWide, pixelsHigh);
    if(document()->size().height()>max_height)
    {
        // 控制超过高度后禁止输入
        if(text.length()>0)
        {
            setPlainText(text.left(text.length()-1));
        }
        QTextCursor cursor = textCursor();
        cursor.movePosition(QTextCursor::End);
        setTextCursor(cursor); 
    }
}

void TextWidget::emitTextUpdated()
{
    adjustSize();
    emit textUpdated(this->toPlainText());
}
